package com.dream.cgomall.configura.redis;

import com.dream.cgomall.dao.CgoOrderDao;
import com.dream.cgomall.emnus.OrderStatusEnum;
import com.dream.cgomall.entity.CgoOrder;
import com.dream.cgomall.util.RedisUtil;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired
    private CgoOrderDao cgoOrderDao;
    @Autowired
    private RedisUtil redisUtil;
    private Gson gson = new Gson();

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * Redis-key失效监听事件，所有key 失效都会走此方法
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //  获取失效的key
        String expiredKey = message.toString();
        System.out.println(expiredKey);
        // 指定key 的前缀=order:，处理对应业务逻辑，可看步骤三生成订单号：public static final String   ORDER_OVER_TIME_KEY= "order-over-time:";
        if (expiredKey.indexOf("order:") != -1) {
            String s = redisUtil.getRedis(expiredKey + "EX");
            if (gson.fromJson(s, CgoOrder.class) != null) {
                long id = gson.fromJson(s, CgoOrder.class).getId();
                if (cgoOrderDao.findStatusByOrderId(id) == 0) {
                    cgoOrderDao.updateOrderStatus(id, OrderStatusEnum.ORDER_CANCEL.status);
                }
            }
        }
        return;
    }
}